Skip to main content

Spread Operator and Rest Parameters

Rest Parameters

tip
  • ... This argument collects all the remaining arguments of the function in an array.
  • the ... must be presented at the end of the method arguments.
function testMethod(name, age, ...others) {
// The output is : [ 'java', 'react', 'vue' ]
console.log(others)
}
testMethod('Jonathan', 89, 'java', 'react', 'vue')

Spread a string

let spreadingStrings = 'abc';
let charArray = [ ...spreadingStrings ];
console.log(charArray) // [ 'a', 'b', 'c' ]

Spread arguments in a function

sum function
function sumArgs() {
var result = 0;
for( var i = 0; i < arguments.length; ++i ) {
result += arguments[i];
}
return result;
}
too many parameters in ES5
var arr = []
for( var i = 0; i < 100; ++i ) arr[i] = Math.random()
console.log("Sum:\t"+sumArgs.apply( null, arr ))
too many parameters in ES6
var arr = []
for( var i = 0; i < 100; ++i ) arr[i] = Math.random()
console.log("Sum:\t"+sumArgs(...arr))

Ignore some of the parameters

[, ...A] = [1,2,3,4] // 1 is ignored.
// A becomes [2,3,4]